/**
 * Created by Administrator on 2016/10/20.
 */
$(function(){
    $(document).on(
        {
            keyup:function(){
                num(this);
            },
            paste:function(){
                num(this);
            }
        },'.decimal'
    )

    $(document).on(
        {
            keyup:function(){
                this.value = this.value.replace(/[^\d]/g,""); //清除"数字"和"."以外的字符
            },
            paste:function(){
                this.value = this.value.replace(/[^\d]/g,""); //清除"数字"和"."以外的字符
            }
        },'.number'
    )
});

function num(obj){
    obj.value = obj.value.replace(/[^\d.]/g,""); //清除"数字"和"."以外的字符
    obj.value = obj.value.replace(/^\./g,""); //验证第一个字符是数字
    obj.value = obj.value.replace(/\.{2,}/g,"."); //只保留第一个, 清除多余的
    obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
    obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3'); //只能输入两个小数
}


function pcajaxsubmits(url,form,message,tishi,jumpurl,fun,isallresult,completefun){
    if(typeof (layer)=='undefined'){
        alert('需要加载layer.js');
        return false
    }
    if(typeof (tishi)=="undefined"||tishi==''){
        tishi='加载中';
    }
    var cc;
    $.ajax({
        url:url,
        type:'post',
        data:form,
        dataType:'json',
        beforeSend:function(){
            cc=layer.msg(tishi, {time:0,offset:'300px',icon: 16,skin:'layui-layer-ajaxsubmits layui-layer-hui'});
        },
        success:function(result){
            if(result.code==0){
                layer.msg(result.message,{icon:2});
                return false;
            }
            var data=result.data;
            if(typeof (fun)=="undefined"||fun==''){
                layer.msg(message,{
                    time: 2000 //不自动关闭
                    ,offset:'300px'
                    ,icon:1
                    //,shade:0.7
                },function(index, layero){ //或者使用btn1
                    if(typeof (jumpurl)=="undefined"||jumpurl==''){
                        location.reload();
                    }else{
                        location.href=jumpurl;
                    }
                });
            }else{
                if(isallresult==true){
                    fun(result);
                }else{
                    fun(data);
                }
            }
        },
        complete:function(){
            layer.close(cc);
            if(!(typeof (completefun)=="undefined"||completefun=='')){
                completefun();
            }
        }
    });
}

function ajaxUrl(url,form,fun,async,isresult){
    if(typeof (layer)=='undefined'){
        alert('需要加载layer.js');
        return false
    }
    if(typeof (async)=='undefined'){
        async=true;
    }
    $.ajax({
        url:url,
        type:'post',
        data:form,
        dataType:'json',
        async:async,
        beforeSend:function(){
        },
        success:function(result){
            if(result.code==0){
                layer.msg(result.message,{icon:2});
                return false;
            }
            var data=result.data;
            if(typeof (fun)=="undefined"||fun==''){
                layer.msg(result.message,{
                    time: 2000 //不自动关闭
                    ,skin:'layui-layer-ajaxsubmits layui-layer-hui'
                    ,offset:'300px'
                    //,shade:0.7
                },function(index, layero){ //或者使用btn1
                    location.reload();
                });
            }else{
                fun(data);
            }
        }
    });
}

//简单表单验证
function formvalid(div){
    div.validate({
        event:"blur",
        onkeyup: false,
        ignore: ".ignore", // 忽略验证的
        errorElement: "em", // 用什么标签标记错误，默认的是label你可以改成em
        errorPlacement: function(error, element) {
            /*
             errorPlacement:Callback  Default: 把错误信息放在验证的元素后面
             指明错误放置的位置，默认情况是：error.appendTo(element.parent());即把错误信息放在验证的元素后面
             */
            error.appendTo( element.parent() ); //element.parent("td")
            error.parent().find("span").remove(); // 验证时，删除提示的标签，存在的时候删除
        },
        success: function(label) {
            label.addClass("success");
        }
    });
}

//图片上传
function upinit(bid,serverurl,inputselecter,fun,data){
    if(typeof (data)=="undefined"||data==''){
        data={
            "thumb_width":"0",
            "thumb_height":"0"
        };
    }
    var uploader = WebUploader.create({
        auto:true,
        // swf文件路径
        swf: 'webuploader/Uploader.swf',

        // 文件接收服务端。
        server:serverurl,

        formData:data,
        accept:{
            title: '图片文件',
            extensions: 'gif,jpg,jpeg,bmp,png',
            mimeTypes: 'image/*'
        },
        thumb:{
            width: '110',
            height: '110'
        },
        chunked: false,
        chunkSize:1000000,
        // 选择文件的按钮。可选。
        // 内部根据当前运行是创建，可能是input元素，也可能是flash.
        pick: '#'+bid,

        // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
        resize: false
    });
    uploader.onUploadSuccess = function( file, response ) {
        if(typeof (fun)=="undefined"||fun==''){
            var parent=$('#'+bid).parent();
            if(parent.find('img').length>0){
                parent.find('img').attr('src',response.path);
            }else{
                parent.append('<img src="'+response.path+'" class="photo">');
            }
            inputselecter.val(response.path);
        }else{
            fun(file,response);
        }

    }

}
function layuipage(pages,curr,jump,cont){
    if(typeof (cont)=="undefined"||cont==''){
        cont="page";
    }
    layui.use(['laypage'], function(){
        var laypage = layui.laypage;
        laypage({
            cont: cont
            ,pages: pages //总页数
            ,first: 1
            ,last: pages
            ,curr:curr
            ,skin: '#1E9FFF'
            ,skip: true
            //,jump: function(obj, first){
            //
            //}
            ,jump: jump
        });
    });
}

function getcurrpage(){
    url=location.href;
    var arr=url.split("#");
    var currpage=parseInt(arr[1]);
    return currpage>0?currpage:1;
}


function updatefield(url,div,fields,data_id,fun){
    $(document).on('click',div, function () {
        var ids=$(this).attr(data_id);
        var text=$(this).text();
        $(this).parent().html('<input type="text" class="updatefield" value="'+text+'" data_c="updatefield"/>');
        var field=$('[data_c="updatefield"]');
        field.focus();
        field.blur(function(){
            var values=$(this).val();
            //{table:table,id:id,field:field,value:value}
            $.post(url,{id:ids,values:values,fields:fields,type:'field'},function(result){
                fun(result);
            },'json');
            return false;
        })
    });
}

function layer_type_1(title,html,width,height){
    if(typeof (width)=="undefined"||width==''){
        width="700px";
    }
    if(typeof (height)=="undefined"||height==''){
        height="90%";
    }
    var area=[width,height];
    if(height=="auto"&&width=='auto'){
        area="auto";
    }


    return layer.open({
        type: 1,
        title:title,
        shadeClose: false,
        shade: 0.8,
        area: area,
        maxWidth:700,
        content: html,
        offset:'5%'
    });
}

function layer_type_and_btn(title,html,fun,width,height){
    if(typeof (width)=="undefined"||width==''){
        width="700px";
    }
    if(typeof (height)=="undefined"||height==''){
        height="90%";
    }
    if(typeof (fun)=="undefined"||fun==''){
        fun=function(){

        };
    }
    return layer.open({
        type: 1,
        title:title,
        shadeClose: false,
        shade: 0.8,
        area: [width,height],
        content: html,
        btn:['确定','取消'],
        yes:fun
    });
}


function layer_type_2(title,html,width,height){
    if(typeof (width)=="undefined"||width==''){
        width="700px";
    }
    if(typeof (height)=="undefined"||height==''){
        height="90%";
    }
    return layer.open({
        type: 2,
        title:title,
        shadeClose: false,
        shade: 0.8,
        area: [width,height],
        content: html
    });
}


function load_message(message){
    return layer.msg(message, {time:0,offset:'300px',icon: 16,skin:'layui-layer-ajaxsubmits layui-layer-hui'});
}

//时间格式化扩展
Date.prototype.Format = function(format){

    var o = {

        "M+" : this.getMonth()+1, //month

        "d+" : this.getDate(), //day

        "h+" : this.getHours(), //hour

        "m+" : this.getMinutes(), //minute

        "s+" : this.getSeconds(), //second

        "q+" : Math.floor((this.getMonth()+3)/3), //quarter

        "S" : this.getMilliseconds() //millisecond

    }

    if(/(y+)/.test(format)) {

        format = format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));

    }

    for(var k in o) {

        if(new RegExp("("+ k +")").test(format)) {

            format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));

        }

    }

    return format;

}


function formatSeconds(value) {

    var theTime = parseInt(value);// 秒

    var theTime1 = 0;// 分

    var theTime2 = 0;// 小时

    if(theTime > 60) {

        theTime1 = parseInt(theTime/60);

        theTime = parseInt(theTime%60);

        if(theTime1 > 60) {

            theTime2 = parseInt(theTime1/60);

            theTime1 = parseInt(theTime1%60);

        }

    }

    var result = ""+parseInt(theTime)+"秒";

    if(theTime1 > 0) {

        result = ""+parseInt(theTime1)+"分"+result;

    }

    if(theTime2 > 0) {

        result = ""+parseInt(theTime2)+"小时"+result;

    }

    return result;

}



function setUserTime(object){
    alert(2);
    var data_sec=$(object).attr('data_sec')
    data_sec=parseFloat(data_sec);
    $(object).text(formatSeconds(data_sec));
}


//新版上传图片

$.zwebupload=function(options){
    var defaults = {
        server:false,
        pick:"",
        auto:true,
        accept: {
            title: 'Images',
            extensions: 'gif,jpg,jpeg,bmp,png',
            mimeTypes: 'image/*'
        },
        formData:{},
        chunked: false,
        SuccessFun: function(){},
    };
    $.extend(defaults,options);
    var LoginTokenName=$.cookie('VipLoginToken');
    defaults.formData.token=LoginTokenName;
    defaults.formData.ajax='ajax';
    var uploader = WebUploader.create({
        auto:defaults.auto,
        swf: 'Uploader.swf',
        server:defaults.server,
        pick:defaults.pick,
        // 开起分片上传。
        chunked:defaults.chunked,
        // 只允许选择图片文件。
        accept:defaults.accept,
        formData:defaults.formData,
    });
    uploader.refresh();
    uploader.on('uploadSuccess', function( file ,result) {
        if(result.code!=1){
            layer.msg(result.message, {icon: 2});
        }else{
            defaults.SuccessFun(result,file);
        }

    });

}



template.helper('getCurrTime', function (Format) {
    if(!Format){
        Format="yyyy-MM-dd hh:mm:ss";
    }
    var date = new Date();
    var currentTime = date.Format(Format);
    return currentTime;
});

